﻿using System;
using System.Collections.Generic;
using Ext.Net;
using System.Linq;
using System.Xml.Linq;
using System.Web.Configuration;
using ZP.Service;
using ZP.Data;
using Kwan.Data;
using Kwan.Helper.Strings;

namespace ZP.Web.Admin
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                Dictionary<string, object> cacheModule = UserUtil.GetModule(UserUtil.GetUserData());
                if (cacheModule == null) Response.Redirect("~/extlogin.aspx");

                Page.Title = WebConfigurationManager.AppSettings["title"];
                btnLoginUser.Text = Page.User.Identity.Name;

                IList<TModule> list = new Expression().List<TModule>();

                IList<TModule> CheckedModule = list.AsQueryable().Where(c => cacheModule.ContainsKey(c.NameEN.ToLower())).ToList();

                var Parent = list.AsQueryable().Where(a => CheckedModule.Any(b => b.Pid == a.EntityID)).ToList() as IList<TModule>;

                var query = from TModule t in Parent
                            select new
                            {
                                Title = t.NameCN,
                                Items = (from TModule tt in CheckedModule.Where(c => c.Pid == t.EntityID)
                                         select new
                                         {
                                             Title = tt.NameCN,
                                             Icon = "resources/images/" + tt.NameEN + ".png",
                                             Id = t.NameEN + "_" + tt.NameEN
                                         })
                            };

                this.Store1.DataSource = query;
                this.Store1.DataBind();

                //DoCreateMenu(null, document.Descendants("group"));

                CreatedModuleMemu(null, CheckedModule, Parent);

                list.Clear();
                CheckedModule.Clear();
                Parent.Clear();
                Store1.Dispose();
            }
        }

        protected void BtnEditPassword_Click(object sender, DirectEventArgs e)
        {
            if (Page.User.Identity.IsAuthenticated)
            {
                TUser tt = (TUser.userName == Page.User.Identity.Name).ListFirst<TUser>();
                this.txtUserID.Text = tt.EntityID.ToString();
                txtUserName.Text = tt.UserName;
                winPassword.Show();
            }
            else
            {
                ExtHelper.ErrorMsg("访问错误", "请重新登录！", this.btnEditPassword.ClientID);
            }
            
        }

        protected void SavePasswordWindow(object sender, DirectEventArgs e)
        {
            TUser tt = (TUser.userName == Page.User.Identity.Name).ListFirst<TUser>();
            if (MD5.Md5Decrypt(tt.Password) == this.txtOldPassword.Text)
            {
                tt.Password = MD5.Md5Encrypt(txtNewPassword.Text);
                DBContext.Save(tt);
                winPassword.Hide();
            }
            else
            {
                ExtHelper.ErrorMsg("验证错误", "旧密码错误！", this.winPassword.ClientID);
            }
        }

        protected void BtnLogout_Click(object sender, EventArgs e)
        {
            UserUtil.Logout();
            string returnUrl = Request.QueryString["returnUrl"];
            returnUrl = returnUrl != null ? returnUrl : "~/Ext/Default.aspx";
            Response.Redirect(returnUrl, true);
        }

        #region 创建Menu(XML)
        private void DoCreateMenu(MenuPanel mp, IEnumerable<XElement> Parent)
        {
            foreach (XElement x in Parent)
            {
                string id = x.Attribute("id").Value;
                string Title = x.Attribute("title").Value;
                if (mp == null)
                {
                    mp = CreateMenuPanel(id, Title);
                    ControlPanel.Items.Add(mp);
                    DoCreateMenu(mp, x.Elements("item"));
                    mp = null;
                }
                else
                {
                    string itemID = mp.ID.Replace("mp_", "") + "_" + id;
                    mp.Menu.Add(CreateMenuItem(itemID, Title, Title));
                    if (x != Parent.Last())
                    {
                        mp.Menu.Add(new MenuSeparator());
                    }
                }
            }
        }
        #endregion

        #region 创建Menu(DataBase)
        private void CreatedModuleMemu(MenuPanel mp, IList<TModule> checkedList, IList<TModule> Parent)
        {
            foreach (TModule t in Parent)
            {
                if (mp == null)
                {
                    mp = CreateMenuPanel(t.NameEN, t.NameCN);
                    ControlPanel.Items.Add(mp);
                    IList<TModule> Child = checkedList.Where(a => a.Pid == t.EntityID).ToList();
                    if (Child.Count > 0)
                    {
                        CreatedModuleMemu(mp, checkedList, Child);
                    }
                    mp = null;
                }
                else
                {
                    string itemID = mp.ID.Replace("mp_", "") + "_" + t.NameEN;
                    mp.Menu.Add(CreateMenuItem(itemID, t.NameCN, "Kwan-icon-" + t.NameEN));

                    //三级目录
                    IList<TModule> Child = checkedList.Where(a => a.Pid == t.EntityID).ToList();

                    if (Child.Count > 0)
                    {
                        MenuItem mt = mp.Menu.Items[mp.Menu.Items.Count - 1] as MenuItem;
                        Menu mu = new Menu();
                        for (int i = 0; i < Child.Count; ++i)
                        {
                            TModule ttt = Child[i];
                            MenuItem mi = CreateMenuItem(itemID + "_" + ttt.NameEN, ttt.NameCN, "Kwan-icon-" + ttt.NameEN);
                            mi.Listeners.Click.Handler = "Kwan.addTab({ tabPanel: #{TabPanel1}, id: 'tab_' + this.id, title: this.text, icon: this.iconCls});";
                            mu.Add(mi);
                        }
                        mt.Menu.Add(mu);
                    }
                    if (t != Parent.Last())
                    {
                        mp.Menu.Add(new MenuSeparator());
                    }
                }
            }
        }
        #endregion

        #region 创建MenuPanel
        /// <summary>
        /// 创建MenuPanel
        /// </summary>
        /// <param name="id"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        private MenuPanel CreateMenuPanel(string id, string text)
        {
            MenuPanel m = new MenuPanel();
            m.ID = "mp_" + id; m.Title = text; m.Expand();
            m.Menu.Listeners.ItemClick.Handler = "Kwan.addTab({ tabPanel: #{TabPanel1}, id: 'tab_' + menuItem.id, title: menuItem.text, icon: menuItem.iconCls});";
            return m;
        }
        #endregion

        #region 创建MenuItem
        /// <summary>
        /// 创建MenuItem
        /// </summary>
        /// <param name="id"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        private MenuItem CreateMenuItem(string id, string text,string iconcls)
        {
            return new MenuItem { ID = id, Text = text, IconCls = iconcls };
        }
        #endregion


    }
}